package com.example.cpl.gjc;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

class NetWorkUtils {


    /**
     * 检查网络是否可用
     *
     * @param paramContext
     * @return
     */
    public static boolean checkEnable(Context paramContext) {
        boolean i = false;
        NetworkInfo localNetworkInfo = ((ConnectivityManager) paramContext
                .getSystemService("connectivity")).getActiveNetworkInfo();
        if ((localNetworkInfo != null) && (localNetworkInfo.isAvailable()))
            return true;
        return false;
    }

    /**
     * 将ip的整数形式转换成ip形式
     *
     * @param ipInt
     * @return
     */
    public static String int2ip(int ipInt) {
        StringBuilder sb = new StringBuilder();
        sb.append(ipInt & 0xFF).append(".");
        sb.append((ipInt >> 8) & 0xFF).append(".");
        sb.append((ipInt >> 16) & 0xFF).append(".");
        sb.append((ipInt >> 24) & 0xFF);
        return sb.toString();
    }

    /**
     * 获取当前ip地址
     *
     * @param context
     * @return
     */
    public static String getLocalIpAddress(Context context) {
        try {

            WifiManager wifiManager = (WifiManager) context
                    .getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            int i = wifiInfo.getIpAddress();
            return int2ip(i);
        } catch (Exception ex) {
            return " 获取IP出错鸟!!!!请保证是WIFI,或者请重新打开网络!\n" + ex.getMessage();
        }
        // return null;
    }
}

public class device_manage extends AppCompatActivity {
    static int dev_num=0;
    TextView dev_login_name,dev_online_num;
    private static final String IP_HEAD = "192.168.31.";
    private static final String TAG = "TAG";
    List<String> list;
    ListView listView;
    ArrayAdapter<String> adapter;
    static Handler mHandler;
    Thread t1;
    String localhost;
    static ExecutorService mThreadPool;
    public final boolean ping(String urld) {
        System.out.println(urld);
        String result = null;
        try {
            String ip = urld;// 除非百度挂了，否则用这个应该没问题(也可以换成自己要连接的服务器地址)
            Process p = Runtime.getRuntime().exec("ping -c 1 -w 1 " + ip);// ping3次
            // 读取ping的内容，可不加。
            InputStream input = p.getInputStream();
            BufferedReader in = new BufferedReader(new InputStreamReader(input));
            StringBuffer stringBuffer = new StringBuffer();
            String content = "";
            while ((content = in.readLine()) != null) {
                stringBuffer.append(content);
            }
            Log.i("TTT", "result content : " + stringBuffer.toString());
            // PING的状态
            int status = p.waitFor();
            if (status == 0) {
                result = "successful~";
                return true;
            } else {
                result = "failed~ cannot reach the IP address";
                return false;
            }

        } catch (IOException e) {
            result = "failed~ IOException";
        } catch (InterruptedException e) {
            result = "failed~ InterruptedException";
        } finally {
            Log.i("TTT", "result = " + result);
        }
        return false;
    }
    @SuppressLint("HandlerLeak")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_manage);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,            //设置全屏
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

        listView=(ListView)findViewById(R.id.device_list);

        dev_login_name=(TextView)findViewById(R.id.dev_login_name);
        dev_online_num=(TextView)findViewById(R.id.dev_online_num);
        dev_login_name.setText(teach_center.who);
        dev_online_num.setText(""+device_manage.dev_num+"");

        list = new ArrayList<String>();
        dev_num=0;
        adapter=new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,list);
        mThreadPool = Executors.newCachedThreadPool();   // 初始化线程池

        NetWorkUtils net=new NetWorkUtils();
        localhost=net.getLocalIpAddress(this);
        System.out.println("localhost: "+localhost);

        mHandler = new Handler()
        {                    // 实例化主线程,用于更新接收过来的消息
            @Override
            public void handleMessage(android.os.Message msg)
            {

                Log.d(TAG, "recv obj: "+msg.obj);
                Log.d(TAG, "recv what: "+msg.what);
                switch (msg.what){
                    case 0x01:
                        dev_num++;
                        list.add(msg.obj.toString());
                        msg.what=0;
                        break;

                }
                listView.setAdapter(adapter);
            }
        };

        t1=new Thread()
        {

            public void run(){

//                String ip=IP_HEAD;
                for(int i=101;i<254;i++) {

                    if(!localhost.equals(IP_HEAD + i)) {         //非自己的IP就ping，因为ping自己会闪退
                        try {

                            if (true == ping(IP_HEAD + i)) {
                                Message msg=new Message();
                                msg.what = 0x01;
                                msg.obj = "故障设置器：" + (i-100);
                                mHandler.sendMessage(msg);
                            }
//                            else{
//                                Message msg=new Message();
//                                msg.what = 0x01;
//                                msg.obj = "故障设置器：" + i;
//                                mHandler.sendMessage(msg);
//                            }
                        }catch (Exception e){
                            System.out.println("catch err for: "+IP_HEAD+i);
                        }
                    }
                }
            }
        };
        t1.start();


    }

    @SuppressLint("PrivateResource")
    @Override
    public void onBackPressed() {       //重写back按键
        super.onBackPressed();

        overridePendingTransition(R.anim.abc_slide_in_bottom, R.anim.abc_slide_out_bottom);

        t1.interrupt();
        System.out.println("按下了back返回键");
        return;
    }
}
